package com.base.myproject.client.HR.holiday;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.Editdisable;
import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.DateUtil;
import com.base.myproject.client.tools.Debug;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.CheckBoxGroup;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;

/**
 * @author cxghiu4102@gmail.com
 * 请假单
 *
 */
public class AskForLeave extends BaseJDBCPanel {

	// 创建一个TabPanel
	String tree_depcode = null;// 讲当前树形结构中选中的部门id保存
	String tree_de_name = null;// 讲当前树形结构中选中的部门name保存
	TabPanel tabPanel = null;
	TreePanel<TreeNodeModelData> treePanel = null;
	BaseTreeStore<TreeNodeModelData> treeWorkStore = null;
	BaseComboBoxX bc2;// 申请人下拉框
	BaseComboBoxX bsb13;// 申请类型
	DateField seach_begin_date = new DateField();// 查询开始日期
	DateField seach_end_date = new DateField();// 查询结束日期
	TextField<String> seach_name = new TextField<String>();// 姓名输入框
	Button seach_bt = new Button("查询");// 查询按钮

	Button bt1 = new Button("同意");// 查询按钮
	Button bt2 = new Button("不同意");// 查询按钮

	private CheckBoxGroup checkGroup = new CheckBoxGroup();
	private CheckBox checkBox8 = new CheckBox();
	DateField date_t2 = new DateField();// 查询日期

	NumberField date_score = new NumberField();// 时长
	PagingToolBar toolBar1 = null;
	
	private List<String> datesList = new ArrayList<String>();
	
	VacationConverter converter = VacationConverter.getConverter();

	public AskForLeave() {
		init();
	}

	public void init() {
		initTreePanel();
		initWeigetx();
		registerMainStore(store);
		registerStore(store);
	}

	public void complete() {
		super.complete();
	}

	private void initWeigetx() {
		toolBar1 = new PagingToolBar(8);

		// 垂直布局
		VerticalPanel vp = new VerticalPanel();
		HorizontalPanel s = new HorizontalPanel();

		s.setHeight("25");
		vp.setSpacing(5);

		s.setVerticalAlign(VerticalAlignment.MIDDLE);
		s.add(new Label("查询时段:"));
		seach_begin_date.setPropertyEditor(new DateTimePropertyEditor(
				"yyyy-MM-dd"));
		s.add(seach_begin_date);
		s.add(new Label("至"));
		seach_end_date.setPropertyEditor(new DateTimePropertyEditor(
				"yyyy-MM-dd"));
		s.add(seach_end_date);
		s.add(new Label("匹配姓名:"));
		s.add(seach_name);
		seach_bt.addListener(Events.OnClick, getListener());
		s.add(seach_bt);
		bt1.addListener(Events.OnClick, getListener());
		s.add(bt1);
		bt2.addListener(Events.OnClick, getListener());
		s.add(bt2);

		vp.add(s);
		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.add(this.getBaseGrid());
		panel2.setBottomComponent(toolBar1);

		vp.add(panel2);
		HorizontalPanel cp2 = new HorizontalPanel();
		cp2.setSpacing(2);
		cp2.add(this.getBaseFormPanel());
		
		HorizontalPanel weekDay = new HorizontalPanel();
		weekDay.setHorizontalAlign(HorizontalAlignment.CENTER);
		weekDay.setVerticalAlign(VerticalAlignment.MIDDLE);
		CheckBox checkBox1 = new CheckBox();
		CheckBox checkBox2 = new CheckBox();
		CheckBox checkBox3 = new CheckBox();
		CheckBox checkBox4 = new CheckBox();
		CheckBox checkBox5 = new CheckBox();
		CheckBox checkBox6 = new CheckBox();
		CheckBox checkBox7 = new CheckBox();

		checkBox1.setBoxLabel("星期一");
		checkBox2.setBoxLabel("星期二");
		checkBox3.setBoxLabel("星期三");
		checkBox4.setBoxLabel("星期四");
		checkBox5.setBoxLabel("星期五");
		checkBox6.setBoxLabel("星期六");
		checkBox6.setValue(true);
		checkBox7.setBoxLabel("星期日");
		checkBox7.setValue(true);
		checkBox8.setValue(true);
		checkBox8.setBoxLabel("法定节日");

		checkGroup.add(checkBox1);
		checkGroup.add(checkBox2);
		checkGroup.add(checkBox3);
		checkGroup.add(checkBox4);
		checkGroup.add(checkBox5);
		checkGroup.add(checkBox6);
		checkGroup.add(checkBox7);
		checkGroup.setHeight(22);
		
		weekDay.add(new Label("指定休息日："));
		weekDay.add(checkGroup);
		weekDay.add(checkBox8);
		
		vp.add(weekDay);
		vp.add(cp2);

		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST,
				200);
		westData.setCollapsible(true);
		westData.setFloatable(true);
		westData.setHideCollapseTool(true);
		westData.setSplit(true);
		westData.setMargins(new Margins(5, 5, 0, 0));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 0, 0, 0));

		ContentPanel center = new ContentPanel();
		center.setScrollMode(Scroll.AUTO);
		center.setHeaderVisible(false);
		center.add(vp);

		ContentPanel panel = new ContentPanel();
		panel.setHeading("选择部门");
		panel.setCollapsible(true);
		panel.add(getTreePanel());
		add(panel, westData);
		add(center, centerData);
	}

	// 创建树形结构的数据表
	BaseTreeStore<TreeNodeModelData> treeStore = null;

	TreePanel<TreeNodeModelData> getTreePanel() {
		if (treePanel == null) {
			initTreePanel();
		}
		return treePanel;
	}

	BaseTreeStore<TreeNodeModelData> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}

	// 创建部门树的数据
	BaseTreeStore<TreeNodeModelData> initTreeStore() {
		StoreInfo si = new StoreInfo();
		si
				.setSql("select icode,id,name from SystemInfo where id is not null order by id asc");
		si.setTreesortcolumn("id");
		si.setKeyname(new String[] { "icode" });
		si.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(si, false);
		treeStore.load();
		return treeStore;

	}

	void initTreePanel() {
		treePanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treePanel.setWidth(200);
		treePanel.setHeight(445);
		treePanel.setBorders(false);
		treePanel.setDisplayProperty("name");
		treePanel.setCheckStyle(CheckCascade.PARENTS);
		treePanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		treePanel.setCheckNodes(CheckNodes.BOTH);
		treePanel.setCheckable(false);
		treePanel.setAutoLoad(true);
		treePanel.setCaching(true);

		treePanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeNodeModelData>>() {
					public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
						String id = be.getItem().get("id").toString();
						tree_depcode = id;
						tree_de_name = be.getItem().get("name").toString();
						set_grid(id);
						bc2.setFilter(" WHERE bcode.bcode = bcode_job.bcode and employstatus = '在职' and systemid like '" + tree_depcode
								+ "%25' ");
					}
				});
	}

	public void setCheckNodes(CheckNodes checkNodes) {
		treePanel.setCheckNodes(checkNodes);
	}

	void set_grid(String id) {
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_Attendance_ot");
		info2.setKeyname(new String[] { "icode" });
		String where = " where 1=1 and ";
		if (id.length() < 5) {
			where = where + " depCode like '" + id + "%25'";
		} else {
			where = where + " depCode = '" + id + "'";
		}
		info2
				.setSql("select c.* from hr_Attendance_ot c,hr_Attendance_holsType b "
						+ where
						+ " and c.holidayType = b.HolsName order by signDate asc");
		grid.getStore().setStoreinfo(info2);
		grid.getStore().reload();
	}

	// 创建一个数据表对象
	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	ModelType type = new ModelType();

	BaseStore<BusiObject> createStore() {

		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);

		type.addField("signDate");
		type.getField("signDate").setType(Date.class);

		type.addField("bcode");
		type.getField("bcode").setType(String.class);

		type.addField("name");
		type.getField("name").setType(String.class);

		type.addField("depCode");
		type.getField("depCode").setType(String.class);

		type.addField("department");
		type.getField("department").setType(String.class);

		type.addField("useDate");
		type.getField("useDate").setType(Date.class);

		type.addField("holidayType");
		type.getField("holidayType").setType(String.class);
		
		type.addField("type");
		type.getField("type").setType(String.class);

		type.addField("Bgntime1");
		type.getField("Bgntime1").setType(Date.class);

		type.addField("Endtime1");
		type.getField("Endtime1").setType(Date.class);

		type.addField("Bgntime2");
		type.getField("Bgntime2").setType(Date.class);

		type.addField("Endtime2");
		type.getField("Endtime2").setType(Date.class);

		type.addField("status");
		type.getField("status").setType(String.class);

		type.addField("batchNo");
		type.getField("batchNo").setType(String.class);

		type.addField("period");
		type.getField("period").setType(Double.class);

		type.addField("C_period");
		type.getField("C_period").setType(Double.class);

		type.addField("remark");
		type.getField("remark").setType(String.class);

		type.addField("readOnly");
		type.getField("readOnly").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_Attendance_ot");
		info.setKeyname(new String[] { "icode" });
		info
				.setSql("select * from hr_Attendance_ot where 1=2 order by signDate asc");
		store = new BaseStore<BusiObject>(type, info);
		store.addEditdisableItem(new Editdisable("readOnly", "1",
				BaseStore.EditDisableType.EQUALS));
		return store;
	}

	// 创建一个grid
	BaseGrid<BusiObject> grid = null;

	BaseGrid<BusiObject> getBaseGrid() {
		if (grid == null) {
			createGrid();
		}

		return grid;
	}

	DateField dateField1;

	void createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		dateField1 = new DateField();
		
		ColumnConfig C11 = new ColumnConfig("status", "审批状态", 60);
		columns.add(C11);
		
		ColumnConfig C2 = new ColumnConfig("bcode", "员工编号", 60);
		columns.add(C2);
		
		ColumnConfig C3 = new ColumnConfig("name", "申请人", 60);
		GridCellRenderer<ModelData> renderer = new GridCellRenderer<ModelData>() {
			public String render(ModelData model, String property,
					ColumnData d, int rowIndex, int colIndex,
					ListStore<ModelData> store, Grid<ModelData> grid) {
				if (model.get(property) != null
						&& model.get(property) instanceof ModelData) {
					return ((ModelData) model.get(property)).get("value");
				}
				return model.get(property);
			}
		};
		// ----
		C3.setRenderer(renderer);
		columns.add(C3);
		
		ColumnConfig C5 = new ColumnConfig("useDate", "发生日期", 80);
		C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C5);
		
		ColumnConfig C1 = new ColumnConfig("signDate", "填表日期", 80);
		C1.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C1.setEditor(new CellEditor(dateField1));
		C1.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C1);

		ColumnConfig C6 = new ColumnConfig("holidayType", "假期类型", 60);
		C6.setRenderer(holidayCode);
		columns.add(C6);

		ColumnConfig C14 = new ColumnConfig("C_period", "计算时长", 60);
		columns.add(C14);

		ColumnConfig C4 = new ColumnConfig("department", "部门名称", 80);
		C4.setHidden(true);
		columns.add(C4);

		ColumnConfig C7 = new ColumnConfig("Bgntime1", "起始时间", 120);
		C7.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		columns.add(C7);

		ColumnConfig C8 = new ColumnConfig("Endtime1", "结束时间", 120);
		C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		columns.add(C8);

		ColumnConfig C15 = new ColumnConfig("remark", "说明", 80);
		C15.setHidden(true);
		columns.add(C15);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm) {
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (tree_depcode == null) {
					MessageBox.alert("警告", "请选择一个部门后再添加新信息", null);
					return;
				}
				
				if (tree_depcode.length() != 6) {
					MessageBox.alert("警告", "添加只能对小部门进行操作，请选择小部门后再操作，谢谢！",
							null);
					return;
				}
				HashMap hp = new HashMap();

				java.util.Date currentTime = new java.util.Date();
				Date df_date = new Date();
				df_date.setYear(currentTime.getYear());
				df_date.setMonth(currentTime.getMonth());
				df_date.setDate(currentTime.getDate());

				hp.put("signDate", df_date);
				hp.put("depCode", tree_depcode);
				hp.put("type", "请假");
				hp.put("department", tree_de_name);

				grid.getStore().add(hp);
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.addListener(Events.AfterEdit, getListener());
		grid.addListener(Events.OnClick, getListener());
		grid.setSelectionModel(cbs);
		grid.setLoadMask(true);
		grid.setBorders(false);
		grid.setSize(782, 258);
		// grid.getView().refresh(true);

	}

	// 创建一个form
	BaseFormPanel form = null;
	DateField C_data8 = new DateField(); // 结束时间1
	TextField<String> C_2 = new TextField<String>();// 员工编号
	DateField C_data7 = new DateField(); // 开始时间1
	NumberField C_num14 = new NumberField(); // 计算时长
	DateField C_data9 = new DateField(); // 开始时间2
	DateField C_data10 = new DateField(); // 结束时间2
	NumberField C_num13 = new NumberField(); // 时长
	DateField C_data1 = new DateField(); // 填表日期
	TextField<String> C_num11;// 审批状态
	DateField happenDate = new DateField();
	BaseComboBoxForm<BaseObject> holidayCode = new BaseComboBoxForm<BaseObject>("HolsCode", "HolsName", "hr_Attendance_holsType", " where 1=1", true);

	BaseFormPanel getBaseFormPanel() {
		if (form == null) {
			createForm();
		}
		return form;
	}

	void createForm() {
		form = new BaseFormPanel(getStore(), false);
		TableLayout tl = new TableLayout(8);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.MIDDLE);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);
		form.setWidth(780);

		form.add(new Label("申请人:"), td);
		bc2 = new BaseComboBoxX("bcode.bname", "bcode, bcode_job", " WHERE bcode.bcode = bcode_job.bcode and employstatus = '在职' and systemid like '%25"
				+ tree_depcode + "%25'");
		bc2.setAllowBlank(false);
		bc2.addListener(Events.Changed, getListener());
		bc2.setName("name");
		form.add(bc2, td);

		form.add(new Label("员工编号:"), td);
		C_2.setEnabled(false);
		C_2.setFireChangeEventOnSetValue(true);
		C_2.setName("bcode");
		form.add(C_2, td);

		form.add(new Label("部门名称:"), td);
		TextField<String> C_num4 = new TextField<String>();
		C_num4.setEnabled(false);
		C_num4.setName("department");
		form.add(C_num4, td);

		form.add(new Label("假期类型:"), td);
		holidayCode.setName("holidayType");
		holidayCode.addListener(Events.Changed, getListener());
		holidayCode.setAllowBlank(false);
		form.add(holidayCode, td);

		form.add(new Label("起始时间:"), td);
		C_data7.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		C_data7.addListener(Events.Changed, getListener());
		C_data7.setFireChangeEventOnSetValue(true);
		C_data7.setAllowBlank(false);
		C_data7.setName("Bgntime1");
		form.add(C_data7, td);

		form.add(new Label("结束时间:"), td);
		C_data8.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		C_data8.addListener(Events.Changed, getListener());
		C_data8.setFireChangeEventOnSetValue(true);
		C_data8.setAllowBlank(true);
		C_data8.setName("Endtime1");
		form.add(C_data8, td);

		form.add(new Label("发生日期:"), td);
		happenDate.setEnabled(false);
		happenDate.addListener(Events.Changed, getListener());
		happenDate.setFireChangeEventOnSetValue(true);
		happenDate.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		happenDate.setName("useDate");
		form.add(happenDate, td);

		form.add(new Label("填表日期:"), td);
		C_data1.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		C_data1.setReadOnly(true);
		C_data1.setName("signDate");
		form.add(C_data1, td);

		form.add(new Label("时长:"), td);
		C_num13.setPropertyEditorType(Double.class);
		C_num13.addListener(Events.Changed, getListener());
		C_num13.setFireChangeEventOnSetValue(true);
		C_num13.setName("period");
		form.add(C_num13, td);

		form.add(new Label("计算时长:"), td);
		C_num14.setPropertyEditorType(Double.class);
		C_num14.setFireChangeEventOnSetValue(true);
		C_num14.setName("C_period");
		C_num14.setEnabled(false);
		form.add(C_num14, td);

		form.add(new Label("说明:"), td);
		TextField<String> C_num15 = new TextField<String>();
		C_num15.setName("remark");
		form.add(C_num15, td);
		form.inited(145);

		form.add(new Label("审批状态:"), td);
		C_num11 = new TextField<String>();
		C_num11.setWidth(126);
		C_num11.setEnabled(false);
		C_num11.setName("status");
		form.add(C_num11, td);
	}
	
	DateTimeFormat dateFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
	String filterSql;
	String sqlOfDetailDatesOfThisLeave;
	//操作的请假单的信息
	String bcode;
	String code;
	String startDate;
	String endDate;
	String holidayName;
	String icode;
	int thisYear;
	int lastYear;
	
	/* (non-Javadoc)
	 * @see com.base.myproject.client.ui.BaseJDBCPanel#save()
	 * 判断用户请假别超过定义的请假天数
	 */
	protected void save() { 
		String status = "";
		
		if (getStore().getValue("status") != null)
			status = getStore().getValue("status").toString();
		
		if (status.equals("同意") && getStore().getValue("useDate") == null) {
			if (getStore().getValue("bcode") == null ||
					getStore().getValue("Bgntime1") == null || getStore().getValue("Endtime1") == null ||
					holidayCode.getValueCode().equals("")) {
				MessageBox.alert("提示", "请填写关键的字段，如果请的半天事假或病假，请填写发生日期。谢谢", null);
				return;
			}
			
			bcode = getStore().getValue("bcode").toString();
			icode = getStore().getValue("icode").toString();
			code = holidayCode.getValueCode();
			holidayName = holidayCode.getRawValue();
			startDate = dateFormat.format((Date)getStore().getValue("Bgntime1"));
			endDate = dateFormat.format((Date)getStore().getValue("Endtime1"));
			thisYear = Integer.parseInt(startDate.substring(0, 4));
			lastYear = thisYear - 1;
			
			MessageBox.confirm("确认", "你确定为员工编号为‘" + bcode + "‘的员工申请" + startDate
					+ "到" + endDate + "的" + holidayName + "么？", new Listener<MessageBoxEvent>() {
						@Override
						public void handleEvent(MessageBoxEvent be) {
							if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
								initSqlOfVacationDetail();
								vacationDatesJudge();
							}
						}
			});
		} else {
			super.save();
		}
	}
	
	/**
	 * 判断请假的天数是否超过规定的请假类型所拥有的最大请假天数（same timeSolt or sum dates of yearVacation）
	 */
	private void vacationDatesJudge() {
		String searchExistsVacationTest = "select top 1 * from dbo.hr_Attendance_vacationManagement where startdate <=getdate() and (enddate is null or enddate >= getdate()) and dateTest is not null and holidayCode = '" + code + "'";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(searchExistsVacationTest, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(DataSet result) {
				int row = result.getRowCount();
				if (row == 0) {// 返回结果为0
					allOperateForSuccee();
				} else {
					String sql = getVacationDatesTestSql(result);
					final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
					greetingService2.getDataSet(sql,new AsyncCallback<DataSet>() {
						@Override
						public void onFailure(Throwable caught) {

						}

						@Override
						public void onSuccess(DataSet result) {
							int row = result.getRowCount();
							if (row > 0) {// 返回结果为0
								allOperateForSuccee();
							} else {
								MessageBox.alert("提示", "请假天数大于该请假类型所规定的天数，请重新选择区间，谢谢", null);
							}
						}
					});
				}
			}
		});
	}
	
	/**
	 * 如果该请假单不用验证或请假天数没有超过他可以请假的天数的话，则调用这个方法做INSERT等操作
	 */
	private void allOperateForSuccee() {
		//insert到记录时间的表里
		String sql = getInsertToVacationDayTableSql();
		sendSql(sql);
	}
	
	/**
	 * get insert sql of this leave
	 * @return get insert sql of this leave
	 */
	private String getInsertToVacationDayTableSql() {
		StringBuilder insertSql = new StringBuilder();
		insertSql.append("insert vacationDetail(code, bcode, vacationDay) ");
		insertSql.append(sqlOfDetailDatesOfThisLeave);
		return insertSql.toString();
	}
	
	/**
	 * get sql of sum dates of this leave or this year
	 */
	private void initSqlOfVacationDetail() {
		StringBuilder sql = new StringBuilder();
		
		sql.append("(");
		sql.append(getSqlOfDetailDatesOfThisLeave());
		if (code.equals("AL")) {
			sql.append(" union select code, vacationDetail.bcode,vacationDay from ");
			sql.append("vacationDetail inner join ");
			sql.append("bcode_job on bcode_job.bcode = vacationDetail.bcode left join ");
			sql.append("(select bcode, requestProlongDate as thisDate from ");
			sql.append("prolongYearVacationRequest where year = '");
			sql.append(thisYear);
			sql.append("') as this on this.bcode = bcode_job.bcode left join ");
			sql.append("(select bcode, requestProlongDate as lastDate from ");
			sql.append("prolongYearVacationRequest where year = '");
			sql.append(lastYear);
			sql.append("' ");
			sql.append(") as last on last.bcode = bcode_job.bcode ");
			sql.append("where bcode_job.bcode = '");
			sql.append(bcode);
			sql.append("' and vacationDay >= ");
			sql.append("case ");
			sql.append("when thisDate is null then case when '");
			sql.append(startDate);
			sql.append("' >= '");
			sql.append(thisYear);
			sql.append("' + substring(convert(varchar(10),entrydate,120),5,6) then '");
			sql.append(thisYear);
			sql.append("' + substring(convert(varchar(10),entrydate,120),5,6) ");
			sql.append("else case when ");
			sql.append("lastDate is null then '");
			sql.append(lastYear);
			sql.append("' + substring(convert(varchar(10),entrydate,120),5,6) ");
			sql.append("else dateadd(dd, 1, lastDate) ");
			sql.append("end end else case when '");
			sql.append(startDate);
			sql.append("' > thisDate then dateadd(dd, 1, thisDate) ");
			sql.append("else case when ");
			sql.append("lastDate is null then '");
			sql.append(lastYear);
			sql.append("' + substring(convert(varchar(10),entrydate,120),5,6) ");
			sql.append("else dateadd(dd, 1, lastDate) end end end ");

		}
		sql.append(") as dates");
		filterSql = sql.toString();
	}
	
	/**
	 * get sql of each date of this leave
	 * @return sql of each date of this leave
	 */
	private String getSqlOfDetailDatesOfThisLeave() {
		StringBuilder sql = new StringBuilder();
		
		datesList.clear();
		datesList.addAll(DateUtil.getAllDateOfTimeSlot(startDate, endDate));
		
		sql.append("select * from (");
		sql.append(linkUnionSql(datesList));
		sql.append(") as a where 1=1 ");
		sql.append(getConditionOfValidVacationDates());
		sqlOfDetailDatesOfThisLeave = sql.toString();
		
		return sqlOfDetailDatesOfThisLeave;
	}
	
	/**
	 * link sql with the detail of leave date 
	 * @param datesList detail of leave date list
	 * @return detail of leave date sql
	 */
	private String linkUnionSql(List<String> datesList) {
		StringBuilder dateUnionSql = new StringBuilder();
		for (String s : datesList) {
			dateUnionSql.append("select '");
			dateUnionSql.append(code);
			dateUnionSql.append("' as code, '");
			dateUnionSql.append(bcode);
			dateUnionSql.append("' as bcode, '");
			dateUnionSql.append(s);
			dateUnionSql.append("' as date union ");
		}
		dateUnionSql.delete(dateUnionSql.length() - 7, dateUnionSql.length());
		
		return dateUnionSql.toString();
	}
	
	/**
	 * get sql of condition of filter vacation
	 * @return condition of filter vacation
	 */
	private String getConditionOfValidVacationDates() {
		StringBuilder condition = new StringBuilder();
		for (int i=0; i<7; i++) {
			int day = 0;
			
			if (checkGroup.get(i).getRawValue().equals("true")) {
				day = i == 6 ? 1 : i+2;
				condition.append(" and ");
				condition.append("datepart(weekday, date) != ");
				condition.append(day);
			}
		}
		if (checkBox8.getRawValue().equals("true")) {
			condition.append(" and not exists (select 1 from hr_attendance_holiday where date between bgnDate and endDate)");
		}
		
		return condition.toString();
	}
	
	/**
	 * get sql of test
	 * @param result result of leave dates of vacation
	 * @return sql of test
	 */
	private String getVacationDatesTestSql(DataSet result) {
		String dateTest = result.getValue(0, "dateTest");
		dateTest = converter.convert(dateTest);
		
		StringBuilder testSql = new StringBuilder();
		testSql.append("select * from (select count(1) as vacationDates from ");
		testSql.append(filterSql);
		testSql.append(") as thisVacationDates inner join (select case when '");
		testSql.append(startDate);
		testSql.append("' >= '");
		testSql.append(thisYear);
		testSql.append("' + substring(convert(varchar(10),");
		testSql.append("entrydate,120),5,6) then ");
		testSql.append(thisYear);
		testSql.append(" - datepart(yy, entrydate) else ");
		testSql.append(lastYear);
		testSql.append(" - datepart(yy, entrydate) end ");
		testSql.append("as work_experience,bcode from bcode_job) as work_experience on 1=1 where bcode = '");
		testSql.append(bcode);
		testSql.append("' and case ");
		testSql.append(dateTest);
		testSql.append(" end >= vacationDates");
		
		return testSql.toString();
	}

	/**
	 *根据选择的人员名字获得人员编码
	 */
	public void get_bcode(String name) {
		String sql2 = "select bcode from bcode where bname='" + name + "' and exists(select 1 from bcode_job where bcode = bcode.bcode and employstatus = '在职')";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql2, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(DataSet result) {
				if (result.getValue(0, "bcode").equals("")) {// 返回结果为0
					Info.display("错误信息提示！", "批量排班出错!");
				} else {
					C_2.setValue(result.getValue(0, "bcode"));
				}
			}
		});
	}

	public void get_time_size(DateField d1, DateField d2) {
		String t1 = C_data7.getRawValue();// 起始时间1 2010-07-10 12:00
		String t2 = C_data8.getRawValue();// 结束时间1 2010-07-10 12:00:00
		
		if (!d2.getRawValue().equals("")) {
			if (d1.getRawValue().equals("")) {
				d2.setRawValue("");
				MessageBox.alert("警告", "时间段为两个必须填写！", null);
				return;
			}
			/*
			 * 由于没有找到 时间控件的onchange事件 目前用的是OnBlur 这个事件 每点击一次会触发两次 所以我在这里加了条件
			 * 限制其中的一次出现
			 */

			if (!t1.equals("") && !t2.equals("")) {
				Date date1 = new Date();
				date1 = C_date(t1);
				Date date2 = new Date();
				date2 = C_date(t2);
				float t_size = (float) ((date2.getTime() - date1.getTime()) / (1000 * 60.0 * 60.0));
				
				C_num14.setValue(t_size);
				C_num13.setValue(C_num14.getValue());
			}
		}
	}

	/*
	 * 当选择固定班次的时候获得该班次的时间并附给form中的时间段
	 */

	/**
	 * 过滤
	 * 
	 * @param store
	 * @param parent
	 * @param record
	 * @param property
	 * @param filter
	 * @return ajax 查询
	 */
	protected boolean Select(Store<BusiObject> store, BusiObject parent,
			BusiObject record, String property, String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {

			Object name = record.get(type.getField(i).getName());

			// TODO
			if (name != null
					&& name.toString().indexOf(filter.toLowerCase()) != -1) {
				return true;
			}
		}

		return false;
	}

	public Date C_date(String date) {
		Date d1 = new Date();
		d1.setYear(Integer.parseInt(date.substring(0, 4)) - 1900);
		d1.setMonth(Integer.parseInt(date.substring(5, 7)) - 1);
		d1.setDate(Integer.parseInt(date.substring(8, 10)));
		d1.setHours(Integer.parseInt(date.substring(11, 13)));
		d1.setMinutes(Integer.parseInt(date.substring(14, 16)));
		return d1;
	}

	/************************************/

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(seach_bt)) {
								String bdate = seach_begin_date.getRawValue();
								String edate = seach_end_date.getRawValue();
								String name = seach_name.getRawValue();
								
								if (edate.equals("") || bdate.equals("")) {
									MessageBox.alert("警告", "请选择一个完整的区间，谢谢",
											null);
									return;
								}
								
								if (tree_depcode == null) {
									MessageBox.alert("警告", "请先选择一个所属部门后再操作!",
											null);
									return;
								}
								String where = " where type = '请假' and depcode like '"
										+ tree_depcode + "%25'";
								if (!bdate.equals("") && !edate.equals("")) {
									where += " and (bgntime1 between '" + bdate
											+ "' and '" + edate + "' or endtime1 between '" + bdate
											+ "' and '" + edate + "') ";
								}
								if (!name.equals("")) {
									where += " and name like '%25" + name
											+ "%25'";
								}
								String sql = "select * from hr_Attendance_ot "
										+ where
										+ " order by signDate asc";
								grid.getStore().getStoreinfo().setSql(sql);
								grid.getStore().reload();
							}
							if (be.getSource().equals(bt1)) {
								for (BusiObject md : grid.getSelectionModel()
										.getSelectedItems()) {
									int index = grid.getStore().indexOf(md);
									grid.setValue(index, "status", "同意");
									C_num11.setRawValue("同意");
								}
								// grid.getStore().reload();
							}
							if (be.getSource().equals(bt2)) {
								for (BusiObject md : grid.getSelectionModel()
										.getSelectedItems()) {
									int index = grid.getStore().indexOf(md);
									grid.setValue(index, "status", "不同意");
									C_num11.setRawValue("不同意");
								}
							}
						} else if (be.getType() == Events.Changed) {
							/*********************/
							if ((be.getSource().equals(C_data7)
									|| be.getSource().equals(C_data8)) && !happenDate.getRawValue().equals("")) {
								get_time_size(C_data7, C_data8);
							} else if (be.getSource().equals(happenDate)) {
								C_data7.setValue(happenDate.getValue());
								C_data8.setValue(happenDate.getValue());
							} else if (be.getSource().equals(bc2)) {
								get_bcode(bc2.getRawValue());
							} else if (be.getSource().equals(C_num13)) {
								if (!C_num13.getRawValue().equals("")) {
									float a = Float.parseFloat(C_num13
											.getRawValue());
									float b = Float.parseFloat(C_num14
											.getRawValue());
									if (a > b) {
										C_num13.setValue(b);
										MessageBox.alert("警告",
												"'时长'不能大于'计算时长'！", null);
										return;
									}
								}
							} else if (be.getSource().equals(holidayCode)) {
								if (holidayCode.getRawValue().equals("病假") || holidayCode.getRawValue().equals("事假")) {
									happenDate.setEnabled(true);
								} else {
									happenDate.setEnabled(false);
									happenDate.setValue(null);
									C_num14.setValue(null);
									C_num13.setValue(null);
								}
							}
							/*************************/

						} else if (be.getType() == Events.AfterEdit) {
							GridEvent<BusiObject> ge = (GridEvent) be;
							int index = ge.getRowIndex();
							if (ge.getProperty().equals("period")) {// 可同时监听多个字段ge.getProperty().equals("amount")
								// ||
								float a = Float.parseFloat(grid.getValue(index,
										"period").toString());
								float b = Float.parseFloat(C_num14
										.getRawValue());
								if (a > b) {
									grid.setValue(index, "period", b);
									MessageBox.alert("警告", "'时长'不能大于'计算时长'！",
											null);
									return;
								}
							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}

							}

						}

					}

				} finally {

					sync--;

				}

			}

		};
		return defaultlistener;
	}
	
	private void updateForSuccess(String sql) {
		GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				List<String> sqlList = new ArrayList<String>();
				String updateThisLeaveToReadOnly = "update hr_Attendance_ot set readOnly = 1 where icode = " + icode;
				sqlList.add(updateThisLeaveToReadOnly);
				
				String month = "";
				String day = "";
				StringBuilder sql = new StringBuilder();
				sql.append("update hr_Attendance_schedule set");
				for (int i=0; i < result.getRowCount(); i++) {
					String date = result.getValue(i, "date");;
					day = date.substring(8);
					if (month.equals(""))
						month = date.substring(0, 7);
					
					if (!month.equals(date.substring(0, 7)) || i == result.getRowCount() - 1) {
						sql.deleteCharAt(sql.length() - 1);
						sql.append(" where ym='");
						sql.append(month);
						sql.append("-01' and depCode = '");
						sql.append(tree_depcode);
						sql.append("' and bcode = '");
						sql.append(bcode);
						sql.append("'");
						sqlList.add(sql.toString());
						
						sql.delete(0, sql.length());
						
						sql.append("update hr_Attendance_schedule set");
						sql.append(" r");
						sql.append(Integer.parseInt(day));
						sql.append("='");
						sql.append(code);
						sql.append("',r");
						sql.append(Integer.parseInt(day));
						sql.append("_r=1,");
						
						month = date.substring(0, 7);
					} else {
						sql.append(" r");
						sql.append(Integer.parseInt(day));
						sql.append("='");
						sql.append(code);
						sql.append("',r");
						sql.append(Integer.parseInt(day));
						sql.append("_r=1,");
					}
				}
				
				command(sqlList);
			}
		});
	}

	private boolean sendSql(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							String returnMessage = result.getMessage();
							if (returnMessage.indexOf("失败") > -1) {
								MessageBox.alert("提示", startDate + "到" + endDate + "这个时间段内已经有" + holidayName + "的数据，不能对同一天请假两次，请重新修改请假时间段，谢谢", null);
								return;
							}
							
							//更新排班表
							updateForSuccess(sqlOfDetailDatesOfThisLeave);
							AskForLeave.super.save();
						}
					});
		}
		return true;
	}
	
	private boolean command(List<String> sqlList) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		if (sqlList.size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			for (String sql : sqlList) {
				csql.getV().add(sql);
			}
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							Debug.printf("更新排班成功");
							String sql = "select * from hr_Attendance_ot where type = '请假' and bgntime1 = '" + startDate + "' and endtime1 = '" + endDate + "' and bcode = '" + bcode + "'" ;
							getStore().getStoreinfo().setSql(sql);
							getStore().reload();
						}
					});
		}
		return true;
	}
}
